! function() {
  $(function() {
    function getInputValueToArr() {
      var inputValue =  $('#edit #editFileInput').val() || [];
      if (typeof inputValue === 'string') {
        inputValue = inputValue.split('^M^')

      }
      return inputValue;
    }
    var currentComponentInfoObj = {};
    // layui初始化
    layui.use(['upload', 'form'], function() {
      var upload = layui.upload;
      var form = layui.form;
      var layer = layui.layer;
      // img文件蒙层效果
      $('body').on('mouseenter', '.uploadWrap__imgBox', function() {
        $(this).find('.cover').show();
      }).on('mouseleave', '.uploadWrap__imgBox', function() {
        $(this).find('.cover').hide();
      })
      // 图片放大
      $('body').on('click', '[data-handle="zoomInImg"]', function() {
        checkImg($(this).data('tipsImg'))
      })
      // 删除文件
      $('body').on('click', '[data-handle="deleteFile"]', function() {
        var fileName = $(this).data('filename')
        var _this = this;
        $.ajax({
          url: '/cloud/file/deleteFile',
          type: 'post',
          data: {
            fileName: fileName
          },
          success: function(result) {
            if (result.code === '0') {
              var fileNameArr = getInputValueToArr();
              var index = fileNameArr.indexOf(fileName)
              fileNameArr.splice(index, 1);
              var input = $('#edit #editFileInput').val(fileNameArr.join('^M^'))
              $(_this).parents('.uploadWrap__imgBox').remove();
              layer.msg('删除成功')
            } else if (result.code === '-1'){
              layer.msg('登录超时,即将跳转登录页')
              location.href = '/login';
            } else {
              layer.msg(result.msg)
            }
          },
          error: function() {
            layer.msg('服务器错误')
          }
        })

      })
      /**
       * 删除文件操作
       * @param {*string} fileName 文件名
       */
      function deleteFile (fileName) {
        var fileNameArr = getInputValueToArr();
        var index = fileNameArr.indexOf(fileName)
        fileNameArr.splice(index, 1);
        var input = $('#edit #editFileInput').val(fileNameArr.join('^M^'))
        $(this).parents('.uploadWrap__imgBox').remove();
        layer.msg('删除成功')
      }
      //点击模块获取模块下的所有组件
      $('body').on('click', '[data-code]', function() {
        var moduleCode = $(this).data('code');
        var target = $(this);
        target.parents('.module').eq(0).toggleClass('fold');
        target.parents('.module').eq(0).find('.JT').toggleClass('fa-arrow-circle-o-left');
        if (!target.parents('.module').eq(0).hasClass('fold')) {
          // if ()
          queryComponent(moduleCode)
        }
      })
      

      /**
       * 获取模块下的组件
       * @param {*string} code 模块编码
       */
      function queryComponent(code) {
        $.ajax({
          url: '/cloud/component/getList',
          type: 'post',
          data: {
            moduleCode: code
          },
        }).done(function(data) {
          if (data.code === '0') {
            var web = [];
            var api = [];
            var color = ['', 'CED8E24', 'CD09879', 'CFFAAAA', 'C39CD5D', 'CC3C0C3'];
            for (var i = 0; i < data.data.length; i++) {
              var variable = data.data[i];
              if (variable.type === '1') {
                api.push('<span data-name="' + variable.name + '" data-component-code="' + variable.componentCode + '" class="component-item ' + color[variable.status] + '">' + variable.name + '</span>');
              } else if (variable.type === '2') {
                web.push('<span  data-name="' + variable.name + '" data-component-code="' + variable.componentCode + '" class="component-item ' + color[variable.status] + '">' + variable.name + '</span>');
              }
            }
            var webStr = web.join('');
            var apiStr = api.join('');
            $('#module' + code + ' .api-component .component .component-item').detach();
            $('#module' + code + ' .web-component .component .component-item').detach();
            $('#module' + code + ' .api-component .component').prepend(apiStr);
            $('#module' + code + ' .web-component .component').prepend(webStr);
          } else if (data.code === '-1'){
            layer.msg('登录超时,即将跳转登录页')
            location.href = '/login';
          } else {
            layer.msg(data.msg)
          }
        })
      }
      // 提交新增和修改
      $('body').on('click', '#submitBtn', function() {
      })

      /**
       * 获取组件信息
       * @param {*string} name 组件名
       * @param {*number} componentCode 组件编码
       */
      function queryComponentInfo(name, componentCode, isEdit) {
        $.ajax({
          url: '/cloud/component/select',
          type: 'post',
          data: {
            name: name,
            componentCode: componentCode
          },
          error: function(err) {
            layer.msg('请求数据错误，请稍后重试！');
          }
        }).done(function(data) {
          if (data.code === '0') {
            var arr = [];
            // 配置
            for (var i = 0; i < data.data.configImages.length; i++) {
              arr.push(data.data.configImages[i].name)
            }
            // 文档
            for (var i = 0; i < data.data.documents.length; i++) {
              arr.push(data.data.documents[i].name)
            }
            // 功能预览
            for (var i = 0; i < data.data.functionImages.length; i++) {
              arr.push(data.data.functionImages[i].name)
            }
            var formData = {
              attributes: data.data.attributes,
              configImages: data.data.configImages,
              documents: data.data.documents,
              functionImages: data.data.functionImages,
              arr: arr
            }
            currentComponentInfoObj = formData;
            renderAddAndUpdateForm(formData, isEdit)
          } else if (data.code === '-1'){
            layer.msg('登录超时,即将跳转登录页')
            location.href = '/login';
          } else {
            layer.msg(data.msg)
          }
        })
      }

      // 点击组件获取组件信息
      $('.component').on('click', '.component-item', function() {
        $('#edit').hide();
        var name = $(this).data('name')// 获取组件名称
        var componentCode = $(this).data('componentCode')// 获取组件编码
        queryComponentInfo(name, componentCode);// ajax获取组件信息
      })
      function addAndUpdateComponent(data) {
        var moduleCode = data.moduleCode;
        $.ajax({
          url: '/cloud/component/addOrUpdate',
          type: 'post',
          data: data,
          error: function() { layer.msg('服务器错误，更新失败')}
        })
        .done(function(result) {
          if (result.code === '0') {
            layer.msg('提交成功!')
            queryComponent(moduleCode)
            $('#edit').hide();
          } else if (result.code === '-1'){
            layer.msg('登录超时,即将跳转登录页')
            location.href = '/login';
          } else {
            layer.msg(result.msg, function(){
              //关闭后的操作
            });
          }
        })
      }

      /**
       * 获取表单下面的所有name
       * @param {*string} formId form表单id
       * @return {*object} result 所有name元素的组件 [{name: 123}, {age: 18}]
       */
      function getFormField(formId) {
        var form = $(formId);
        var result = {};
        var field = form.find('[name]');
        field.each(function(index, item) {
          var $item = $(item);
          result[$item.attr('name')] = $item.val();
        })
        return result;
      }

      // 添加组件处理
      $('body').on('click', '.add-btn', function() {
        var componentType = $(this).data('type') + ''
        var $module = $(this).parents('.module');
        var moduleCode = $module.find('.head').data('code');
        var componentCode = $(this).prev('.component-item').data('componentCode') ? ($(this).prev('.component-item').data('componentCode') + 1 + '') : (moduleCode + '' + '001');
        var moduleName = $module.find('.head .modulename').text();
        $('#edit').hide();
        $('#check_component').hide();
        renderAddAndUpdateForm({
          attributes: {
            type: componentType,
            moduleName: moduleName,
            moduleCode: moduleCode,
            componentCode: componentCode,
            add: '1'
          }
        }, true);
      })
      /**
       * 根据数据渲染出表单
       * @param {*object} obj 表单数据对象
       */
      function renderAddAndUpdateForm(obj, isEdit) {
        if (!isEdit) {
          $('#check_component').html(template('check_component_tpl', {
            attributes: obj.attributes || {},
            configImages: obj.configImages || [],
            documents: obj.documents || [],
            functionImages: obj.functionImages || [],
            editFileInput: obj.arr ? obj.arr.join('^M^') : '' // 所有文件集合
          }))
          $('#check_component').show();
          $('[data-toggle="tooltip"]').tooltip();
        } else {
          $('#edit').html(template('editContentTpl', {
            attributes: obj.attributes || {},
            configImages: obj.configImages || [],
            documents: obj.documents || [],
            functionImages: obj.functionImages || [],
            editFileInput: obj.arr ? obj.arr.join('^M^') : '' // 所有文件集合
          }))
          
          var uploader1 = WebUploader.create({
            
                // 选完文件后，是否自动上传。
              auto: true,
          
              // swf文件路径
              swf: '/libs/webuploader/Uploader.swf',
              formData: { moduleType: 1 },
              // 文件接收服务端。
              server: '/cloudFileServer/cloud/file/upload',
          
              // 选择文件的按钮。可选。
              // 内部根据当前运行是创建，可能是input元素，也可能是flash.
              pick: '#test1',
          
              // 只允许选择图片文件。
              accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
              }
          });
          // 文件上传成功，给item添加成功class, 用样式标记上传成功。
          uploader1.on( 'uploadSuccess', function( file, ret ) {
            console.log(ret)
            var inputValue =  getInputValueToArr();
            if (ret.code === 0) {
              layer.msg('上传成功');
              var str = '<span class="uploadWrap__imgBox" style="width: 96px; height: 96px; display: inline-block;">' +
                '<img width="100%" height="100%" src="/cloudFileServer/cloud/file/getImage/'+ ret.data.fileName +'" alt="">' +
                '<span class="cover">' +
                  '<i class="glyphicon glyphicon-zoom-in" data-handle="zoomInImg" data-tips-img="/cloudFileServer/cloud/file/getImage/'+ ret.data.fileName +'"></i>&nbsp;&nbsp;&nbsp;<i data-handle="deleteImg" data-filename="'+ ret.data.fileName +'" class="glyphicon glyphicon-trash"></i>' +
                '</span>' +
              '</span>'
              $('#functionWrap').append(str)
              inputValue.push(ret.data.fileName)
              var input = $('#edit #editFileInput').val(inputValue.join('^M^'))
            }
          });
          uploader1.on('uploadError', function( file ) {
            layer.msg('上传失败');
          });
          uploader1.on( 'fileQueued', function( file ) {
            var imgNum = $('#functionWrap .uploadWrap__imgBox').size();
            if (imgNum < 4) return false;
            layer.msg('sorry! 目前仅支持最多4张图片.'); uploader1.cancelFile( file )
            return false;
          });

          uploader1.on("error",function (type){
            if (type=="Q_TYPE_DENIED"){
                layer.msg('请上传JPG、PNG格式文件')
            }
          });

          var uploader2 = WebUploader.create({
            
                // 选完文件后，是否自动上传。
              auto: true,
          
              // swf文件路径
              swf: '/libs/webuploader/Uploader.swf',
              formData: { moduleType: 2 },
              // 文件接收服务端。
              server: '/cloudFileServer/cloud/file/upload',
          
              // 选择文件的按钮。可选。
              // 内部根据当前运行是创建，可能是input元素，也可能是flash.
              pick: '#test2',
          
              // 只允许选择图片文件。
              accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
              }
          });
          // 文件上传成功，给item添加成功class, 用样式标记上传成功。
          uploader2.on( 'uploadSuccess', function( file, ret ) {
            var inputValue =  getInputValueToArr();
            if (ret.code === 0) {
              layer.msg('上传成功');
              var str = '<span class="uploadWrap__imgBox" style="width: 96px; height: 96px; display: inline-block;">' +
                '<img width="100%" height="100%" src="/cloudFileServer/cloud/file/getImage/'+ ret.data.fileName +'" alt="">' +
                '<span class="cover">' +
                  '<i class="glyphicon glyphicon-zoom-in" data-handle="zoomInImg" data-tips-img="/cloudFileServer/cloud/file/getImage/'+ ret.data.fileName +'"></i>&nbsp;&nbsp;&nbsp;<i data-handle="deleteImg" data-filename="'+ ret.data.fileName +'" class="glyphicon glyphicon-trash"></i>' +
                '</span>' +
              '</span>'
              $('#settingWrap').append(str)
              inputValue.push(ret.data.fileName)
              $('#edit #editFileInput').val(inputValue.join('^M^'))
              return false;
            }
            layer.msg(ret.msg);
          });
          uploader2.on('uploadError', function( file ) {
            layer.msg('上传失败');
          }); 
          uploader2.on( 'fileQueued', function( file ) {
            var imgNum = $('#settingWrap .uploadWrap__imgBox').size();
            if (imgNum < 4) return false;
            layer.msg('sorry! 目前仅支持最多4张图片.'); uploader1.cancelFile( file )
            return false;
          });
          uploader2.on("error",function (type){
            if (type=="Q_TYPE_DENIED"){
                layer.msg('请上传JPG、PNG格式文件')
            }
          });

          var uploader3 = WebUploader.create({
            
                // 选完文件后，是否自动上传。
              auto: true,
          
              // swf文件路径
              swf: '/libs/webuploader/Uploader.swf',
              formData: { moduleType: 3 },
              // 文件接收服务端。
              server: '/cloudFileServer/cloud/file/upload',
          
              // 选择文件的按钮。可选。
              // 内部根据当前运行是创建，可能是input元素，也可能是flash.
              pick: '#documentPicker',
          
              // 只允许选择图片文件。
              accept: {
                title: 'docx',
                extensions: 'docx',
                mimeTypes: 'docx,trf'
              }
          });
          uploader3.on('uploadError', function( file ) {
            layer.msg('上传失败');
          }); 
          // 文件上传成功，给item添加成功class, 用样式标记上传成功。
          uploader3.on( 'uploadSuccess', function( file, ret ) {
            var inputValue =  getInputValueToArr();
            if (ret.code === 0) {
              layer.msg('上传成功');
              var str = '<div class="uploadWrap__imgBox">' +
                '<span>' + ret.data.fileName + '</span>' +
                '<i style="cursor: pointer" data-handle="deleteFile" data-filename="' + ret.data.fileName + '" class="fr glyphicon glyphicon-trash"></i>' +
              '</div>'
              $('#documentWrap').append(str)
              inputValue.push(ret.data.fileName)
              $('#edit #editFileInput').val(inputValue.join('^M^'))
            }
          });
          uploader3.on("error",function (type){
            if (type=="Q_TYPE_DENIED"){
                layer.msg('请上传docx格式文件')
            }
          });
          $('#edit').show();
          $('[data-toggle="tooltip"]').tooltip();
          $('#editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
              valid: 'glyphicon glyphicon-ok',
              invalid: 'glyphicon glyphicon-remove',
              validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
              firstName: {
                  container: '#firstNameMessage',
                  validators: {
                      notEmpty: {
                          message: 'The first name is required and cannot be empty'
                      }
                  }
              },
              name: {
                  validators: {
                      notEmpty: {
                          message: '组件名称不能为空'
                      },
                      stringLength: {
                          min: 1,
                          max: 10,
                          message: '请输入10个字符以内的名称'
                      }
                  }
              },
              cocurrencyCount: {
                  message: 'The username is not valid',
                  validators: {
                      notEmpty: {
                          message: '支持并发数不能为空'
                      },
                      numeric: {message: '支持并发数只能输入数字'},
                      stringLength: {
                          min: 5,
                          max: 8,
                          message: '支持并发数长度为5-8位数字'
                      }
                  }
              },
              responseDuration: {
                  message: '响应时间错误',
                  validators: {
                      notEmpty: {
                          message: '响应时间不能为空'
                      },
                      numeric: {message: '响应时间只能输入数字'},
                      stringLength: {
                          min: 1,
                          max: 2,
                          message: '响应时间为1-100的数值'
                      }
                  }
              },
              componentDescription: {
                  message: '响应时间错误',
                  validators: {
                      notEmpty: {
                          message: '请输入组件相关描述'
                      }
                  }
              }
            }
          })
          .on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();
            var formData = getFormField('#editForm');
            var data = $.extend({}, formData)
            data.fileName = JSON.stringify(formData.fileName.split('^M^'))
            addAndUpdateComponent(data);
        });
        }
      }

      $('body').on('click', 'img[data-tips-img]', function() {
        checkImg($(this).data('tipsImg'))
      })
      $('body').on('click', '#toEdit', function() {
        $('#check_component').hide();
        $('#edit').hide();
        renderAddAndUpdateForm(currentComponentInfoObj, true);
      })
      $('body').on('click', '#updateComponentCode', function() {
        //prompt层
        var oldCode = $(this).data('code') + '';
        layer.prompt({
          value: oldCode,
          title: '输入组件编码，并确认'
        },function(val, index){
          // layer.msg('得到了'+val);
          $.ajax({
            url: '/cloud/component/updateCode',
            type: 'post',
            data: {
              oldCode: oldCode,
              newCode: val
            },
            error: function(error) {layer.msg('服务器错误！修改失败')}
          })
          .done(function(result) {
            if (result.code === '0') {
              $('#edit #editComponentCode').val(val);
              $('#edit #editCode').val(val.slice(4));
              layer.msg('修改成功!');
              queryComponent(oldCode.slice(0, 4))
            } else if (result.code === '-1'){
              layer.msg('登录超时,即将跳转登录页')
              location.href = '/login';
            } else {
              layer.msg(result.msg);
            }
          })
          layer.close(index);
        });
      })
      $('body').on('click', '#closeEditBox', function() {
        $('#edit').hide();
      })
      $('body').on('click', '#closeChickBox', function() {
        $('#check_component').hide();
      })
      $('body').on('click', '[data-handle="closeBox"]', function() {
        $(this).parents('.rightBox').hide();
      })
      $('#addModule').on('click', function() {
        layer.prompt({
          title: '输入模块名称，并确认'
        },function(val, index){
          if(!(/^.{1,10}$/.test(val)) && (/\S+/.test(val))) {
            layer.msg('请输入10个字以内的名称.'); 
            return false;
          };
          $.ajax({
            url: '/cloud/component/addModule',
            type: 'post',
            data: {
              moduleName: val
            },
            error: function(error) {layer.msg('服务器错误！新增失败')}
          })
          .done(function(result) {
            if (result.code === '0') {
              layer.msg('新增成功');
              location.reload();
            } else if (result.code === '-1'){
              layer.msg('登录超时,即将跳转登录页')
              location.href = '/login';
            } else {
              layer.msg(result.msg);
            }
          })
          layer.close(index);
        });
      })
      function checkImg(imgUrl) {
        layer.open({
          type: 1,
          closeBtn: 1,
          title: false,
          area: '1032px',
          skin: 'layui-layer-nobg', //没有背景色
          shadeClose: true,
          content: '<img width="100%" height="100%" src="'+ imgUrl +'" alt="">'
        });
      }
    });
    
  })
}()
